import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.logging.Logger;

public class TcpServer
{
    private ServerSocket serverSocket;
    Logger logger = MyLogger.getLogger();
    private Socket [] clients;

    private int clientCount;

    public int getClientCount() {
        return clientCount;
    }

    public void socketInitial()
    {
        if (Global.thisDeviceType == SelfType.DEVICE_TYPE_CLIENT)
        {
            return;
        }
        try
        {
            serverSocket = new ServerSocket(Global.tcpServerPort); // 监听Global.tcpServerPort端口
            clients = new Socket[20];
            clientCount = 0;
        }
        catch (IOException e)
        {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }

    public void Accept()
    {
        logger.info("Accept");
        try
        {
            Socket socketClient = serverSocket.accept();
            clients[clientCount] = socketClient;
            clientCount++;
        }
        catch (IOException e)
        {
            throw new RuntimeException(e);
        }
    }

    public StateObject receive()
    {
        try
        {
            ObjectInputStream objectInputStream = new ObjectInputStream(clients[0].getInputStream());
            try {
                //从服务器端读取状态信息
                //read state from server, very important.
                StateObject object = (StateObject)objectInputStream.readObject();
                logger.info("Server server receive: " + object.toString());
                return object;
                //logger.info(object.toString());
            }
            catch (ClassNotFoundException e)
            {
                throw new RuntimeException(e);
            }
        }
        catch (IOException e)
        {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }

    /**
     * 这里是将打包好的状态信息从服务器端发送给客户端
     * @param stateObject 打包好的状态信息
     */
    public void send(StateObject stateObject)
    {
        logger.info("Tcp server send: " + stateObject.toString());
        if (clientCount == 0)
        {
            return;
        }
        Socket client = clients[0]; //这里只是取第一个客户端不对，如果有多个客户端，则需要使用多个
        try
        {
            ObjectOutputStream objectOutputStream;
            objectOutputStream = new ObjectOutputStream(client.getOutputStream());

            //这里是将打包好的状态信息从服务器端发送给客户端
            objectOutputStream.writeObject(stateObject);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
